package cn.easyplatform.studio.web.servlet;


import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.StudioUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.InviteVo;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.*;

public class InviteRichlet extends GenericRichlet {

    @Override
    public void service(Page page) throws Exception {
        String s = page.getDesktop().getQueryString();
        String[] content = s.split("&");
        if (content != null && content.length == 4){
            if (content[0].split("=").length == 2 &&
                    content[1].split("=").length == 2 &&
                    content[2].split("=").length == 2 &&
                    content[3].split("=").length == 2) {
                String userID = content[0].split("=")[1];
                String projectId = content[1].split("=")[1];
                String roleId = content[2].split("=")[1];
                String currentToken = content[3].split("=")[1];
                String token = StudioUtil.getLinkToken(userID, projectId,
                        roleId);
                if (currentToken.equals(token)) {
                    InviteVo inviteVo = new InviteVo();
                    inviteVo.setUserID(userID);
                    inviteVo.setProjectID(projectId);
                    inviteVo.setRoleID(roleId);
                    inviteVo.setToken(currentToken);
                    Contexts.setInvite(inviteVo);
                    Executions.getCurrent().sendRedirect("/");
                    return;
                }
            }
        }
        WebUtils.showError(Labels.getLabel("product.link.error"));
    }
    @Override
    public void init(RichletConfig config) {
        super.init(config);
        //initialize resources
    }

    @Override
    public void destroy() {
        super.destroy();
        //destroy resources
    }
}
